﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Office.Interop.Excel;
using NRank.Benchmark.Benchmarking;
using NRank.Benchmark.Queries;

namespace NRank.Benchmark
{
	/// <summary>
	/// Main class for benchmarking.
	/// </summary>
	public class Program
	{
		/// <summary>
		/// Method run when started benchmarking
		/// </summary>
		static void Main()
		{
			const int repeatCount = 3;

			for (int i = 0; i < repeatCount; i++)
			{
				Console.WriteLine("---- ROUND {0} ----", i + 1);

				// gather results
				var benchmarkQueries = BenchmarkQuerySet.Queries.ToList();

				foreach (var query in benchmarkQueries)
				{
					// create excel application
					object misValue = System.Reflection.Missing.Value;
					Application xlApp = new Application { Visible = true };
					Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);
					((Worksheet)xlWorkBook.Worksheets.Item[3]).Delete();
					((Worksheet)xlWorkBook.Worksheets.Item[2]).Delete();

					var xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.Item[1];
					ChartObjects xlCharts = (ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
					ChartObject myChart = xlCharts.Add(30, 280, 500, 300);
					Chart chartPage = myChart.Chart;
					var results = new List<BenchmarkResult>();

					int row = 2;
					int col = 2;

					Console.WriteLine();
					Console.WriteLine("Query: {0}", query.GetType().Name);

					foreach (int k in BenchmarkQuerySet.ValuesOfK)
					{
						// toto jsou mereni vsech algoritmu pro jeden typ dotazu a jedno k
						// tj. jeden radek v excelu
						Console.WriteLine("k: {0}", k);
						var benchmarkResults = query.GetResults(k).ToList();

						xlWorkSheet.Cells[row, 1] = k;

						col = 2;
						foreach (var benchmarkResult in benchmarkResults)
						{
							xlWorkSheet.Cells[row, col++] = benchmarkResult.TimeConsumed.TotalMilliseconds;
							//xlWorkSheet.Cells[row, col++] = benchmarkResult.RightDepth;
							//xlWorkSheet.Cells[1, col - 2] = benchmarkResult.AlgorithmName + " levý zdroj";
							xlWorkSheet.Cells[1, col - 1] = benchmarkResult.AlgorithmName;
						}

						++row;

						results.AddRange(benchmarkResults);
					}

					Range chartRange = xlWorkSheet.Range["A1", misValue];
					chartRange = chartRange.Resize[row - 1, col - 1];
					chartPage.SetSourceData(chartRange, XlRowCol.xlColumns);
					chartPage.ChartType = XlChartType.xlLineMarkers;

					string filename = string.Format("{0}_{1}.xls", DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"), query.GetType().Name);
					xlWorkBook.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), filename));

					//xlWorkBook.Close();

					//xlApp.Quit();

					//Marshal.ReleaseComObject(xlApp);
					//Marshal.ReleaseComObject(xlWorkBook);
					//Marshal.ReleaseComObject(xlWorkSheet);
				}
			}

			Console.WriteLine();
			Console.WriteLine("Done.");
		}
	}
}